package com.riant.controller;

import com.riant.bean.response.BaseRes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname TestCookieController
 * @Description TODO
 * @Date 2022/5/4 12:22
 * @Created by 张斌
 */
@Controller
public class TestCookieController {
    private final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @RequestMapping(path = {"/test12"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseRes test12()  {
        final Cookie[] cookies = request.getCookies();
        String value= "default";
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("name")){
                value=cookie.getValue();
            }
        }
        final Cookie cookie = new Cookie("name","dddd");
        this.response.addCookie(cookie);//向浏览器返回cookie
        final BaseRes success = BaseRes.success();
        success.setData(value);
        return success;
    }

    @RequestMapping(path = {"/test13"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseRes test13() {
        HttpServletRequest requests = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        HttpServletResponse responses = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        final Cookie[] cookies = requests.getCookies();
        String value= "default";
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("name")){
                value=cookie.getValue();
            }
        }
        final Cookie cookie = new Cookie("name","xxxxxx");
        responses.addCookie(cookie);//向浏览器返回cookie
        final BaseRes success = BaseRes.success();
        success.setData(value);
        return success;
    }

}
